package cn.rdtimes.wolfdsp.core.ha;

import cn.rdtimes.wolfdsp.core.job.JobGraphService;
import cn.rdtimes.wolfdsp.core.service.ScheduleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * 缺省实现高可用接口
 *
 * @author BZ
 */
public class DefaultPlatformHAStrategy implements PlatformHAStrategy {
    private static final Logger logger = LoggerFactory.getLogger(DefaultPlatformHAStrategy.class);

    private State state;

    public DefaultPlatformHAStrategy(State state) {
        this.state = state;
    }

    @Override
    public synchronized void changeState(State state) {
        if (getState() == state) {
            logger.info("change state is equal");
            return;
        }

        this.state = state;
        //不为主服务器不能继续调度
        if (!enabledPerform()) return;

        Collection<StateSyncService.StateDTO> stateDTOList = ScheduleManager.getInstance()
                .getStateSyncService().getStateDTOList();
        if (stateDTOList == null || stateDTOList.isEmpty()) return;

        JobGraphService jobGraphService = ScheduleManager.getInstance().getJobGraphService();
        try {
            //重新启动任务流程服务
            jobGraphService.restart();
        } catch (Exception e) {
            logger.error("schedule", e);
            return;
        }
        //继续调度
        for (StateSyncService.StateDTO dto : stateDTOList) {
            try {
                jobGraphService.scheduleContinue(dto.getJobId());
            } catch (Exception e) {
                logger.error("schedule", e);
            }
        }
    }

    @Override
    public synchronized State getState() {
        return state;
    }

}
